public class Museum
{
    private int waitList = 0;
    private int galleryList = 0;

    private static final int WAITLIST_CAPACITY = 3;

    private static void handleWait(Object lock)
    {
        try {
            lock.wait();
        } catch(Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    private synchronized void enterWaitRoom()
    {
        while (waitList >= WAITLIST_CAPACITY) handleWait(this);
        waitList += 1;
        if (waitList >= WAITLIST_CAPACITY) notifyAll();
    }

    private synchronized void enterGallery()
    {
        while (waitList < WAITLIST_CAPACITY) handleWait(this);
        galleryList += 1;
        if (galleryList == WAITLIST_CAPACITY) waitList = 0;
    }

    public synchronized void leave()
    {
        galleryList -= 1;
        if (galleryList == 0)
            notifyAll();
    }

    public void enter()
    {
        enterWaitRoom();
        System.out.println("\t" + Thread.currentThread().getId() + " has entered the waitroom");
        System.out.println("\t" + waitList + " people in the waitroom");
        enterGallery();
    }
}
